//
//  HomeViewController.m
//  Kjs
//
//  Created by maple on 16/4/17.
//  Copyright © 2016年 kjs. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeItemCell.h"
#import "GJAutoCycleScrollView.h"
#import "MBProgressHUD+MAP.h"
#import "ItemDetailViewController.h"
#import "LoginViewController.h"
#import "IndexItemsModel.h"
#import "KJSRequest.h"
#import "AppDelegate.h"
#import "IndexImage.h"
#import "AccountDetailViewController.h"
#import "MoreTableViewController.h"
#import "HomeIntroView.h"
#import "NewsDetailViewController.h"
#define SCREEN_W [[UIScreen mainScreen] bounds].size.width //屏幕宽度
#define SCREEN_H [[UIScreen mainScreen] bounds].size.height //屏幕高度
#define NAV_BAR_H self.navigationController.navigationBar.frame.size.height+20

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,GJAutoCycleScrollViewDataSource,GJAutoCycleScrollViewDelegate>
/*--- tableview ---*/
@property (strong, nonatomic) UITableView *tableView;

@property (strong ,nonatomic) NSArray <ItemInfo *> *items;
@property (strong ,nonatomic) NSArray <IndexImage *> *images;
@property (strong ,nonatomic) GJAutoCycleScrollView *adView;
@property (assign ,nonatomic) int rows;
@property (strong ,nonatomic) HomeIntroView *homeIntroView;
@end

@implementation HomeViewController
//static CGFloat HEIGHT_OF_ADVIEW = 100;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"快金所"];
    self.naviTopView = YES;
    //设置更多按钮
    UIButton* rightButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [rightButton setImage:[UIImage imageNamed:@"index-more"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(goMore) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBtn;

    
    //设置tableview
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HEIGHT_OF_ADVIEW, SCREEN_W, SCREEN_H-NAV_BAR_H-HEIGHT_OF_ADVIEW)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeItemCell" bundle:nil] forCellReuseIdentifier:@"HomeItemCell"];
    
    [self.view addSubview:self.tableView];
    
    //处理tableview分割线 左偏移问题
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    [self configeration];
    [self configurateAdImageView];
    


}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //设置表头
    self.homeIntroView = (HomeIntroView *)[[[NSBundle mainBundle] loadNibNamed:@"HomeIntroView" owner:self options:nil] firstObject];
    self.tableView.tableHeaderView =  self.homeIntroView;
    [self getNewsList];
    //是否自动登录
    if (CurentDelegate.account.partyId){
        [self initIndexData];
    }else{
        [self autologin];
    }
}

#pragma mark - custom method

-(void)getNewsList
{
    [KJSRequest getNewsListWithPage:@"1" rows:@"10" ret:^(PlatformNewsModel *model) {
        NSLog(@"modelhaha=%@",model);
        if (model.success) {
            if ([model.platformTrendsList count] != 0) {
                NSMutableArray *rssArray = [[NSMutableArray alloc] init];
                for (int i = 0 ; i < [model.platformTrendsList count]; i++) {
                    PlatformNews *news = model.platformTrendsList[i];
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                                         news.platformTrendsId,@"id",
                                         news.title,@"title",
                                         nil];
                    [rssArray addObject:dic];
                }
                self.homeIntroView.rssArray = rssArray;
                [self.homeIntroView.newsView.newsButton addTarget:self action:@selector(goNewsDetail) forControlEvents:UIControlEventTouchUpInside];
            }
        }
    }];
    
}
-(void)goNewsDetail
{
    NSLog(@"----------%@",self.homeIntroView.notice_index);
    NewsDetailViewController *newDetailVC = [[NewsDetailViewController alloc] init];
    newDetailVC.platformId = self.homeIntroView.notice_index;
    [self displayViewController:newDetailVC];
}
-(void)initIndexData
{
    if ([self.items count]==0) {
        [self getIndexItems];
    }
    if ([self.images count]==0) {
        [self getIndexImages];
    }
    if (!CurentDelegate.account) {
        //重绘登录按钮
        UIButton* leftButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        leftButton.titleLabel.font=[UIFont systemFontOfSize:14];
        [leftButton setTitle:@"登录" forState:UIControlStateNormal];
        [leftButton addTarget:self action:@selector(goLogin) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
        self.navigationItem.leftBarButtonItem = leftBtn;
        
    }else{
        //设置已登录按钮
        UIButton* leftButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        leftButton.titleLabel.font=[UIFont systemFontOfSize:12];
        // [leftButton setTitle:@"已登录" forState:UIControlStateNormal];
        [leftButton setImage:[UIImage imageNamed:@"account-avatar"] forState:UIControlStateNormal];
        [leftButton addTarget:self action:@selector(goMyAccount) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
        self.navigationItem.leftBarButtonItem = leftBtn;
        
    }

}
- (void)autologin
{
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
    if ([userDefaults objectForKey:@"username"] && [userDefaults objectForKey:@"password"]) {
        NSString *ifAutoLogin = [userDefaults objectForKey:@"ifAutoLogin"];
        if ([ifAutoLogin isEqualToString:@"autoLogin"]) {
            NSString *username = [userDefaults objectForKey:@"username"];
            NSString *password = [userDefaults objectForKey:@"password"];
            [KJSRequest LoginWithUsername:username Password:password ret:^(UserInfo *model){
                if (![model.partyId isEqualToString:@""]) {
                    CurentDelegate.account = model;
                    CurentDelegate.ifReLoad = YES;
                    CurentDelegate.IMuserID = @"zpf";
                    CurentDelegate.IMpassword = @"zpf123";
                }else{
                    [userDefaults setObject:@"unautoLogin" forKey:ifAutoLogin];
                }
                [self initIndexData];
            }];

        }
    }
    [self initIndexData];
}

-(void)getIndexImages
{
    [KJSRequest GetINdexImageWithRet:^(IndexImageModel *model) {
        self.images = model.result;
        [self.adView reloadData];
    }];
}
-(void)getIndexItems
{
    [KJSRequest GetIndexItemsWithRows:self.rows ret:^(IndexItemsModel *model){
        self.items = model.items;
        [self.tableView reloadData];
    }];
    
}

-(void)goLogin{

    NSLog(@"跳转登录界面test");
    LoginViewController *loginVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"];
    loginVC.ifLogin = ^(NSString* partyId)
    {
        //设置已登录按钮
        UIButton* leftButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        leftButton.titleLabel.font=[UIFont systemFontOfSize:12];
        [leftButton setImage:[UIImage imageNamed:@"account-avatar"] forState:UIControlStateNormal];
        [leftButton addTarget:self action:@selector(goMyAccount) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
        self.navigationItem.leftBarButtonItem = leftBtn;
        
    };
    [self displayViewController:loginVC];

}

-(void)goMyAccount
{
    NSLog(@"跳到账户详情界面");
    AccountDetailViewController *accountDetailVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"AccountDetailViewController"];
    [self displayViewController:accountDetailVC];
}

-(void)goMore{
    MoreTableViewController * moreVC = [[MoreTableViewController alloc] initWithViewControllerIdentifier:@"MoreTableViewController"];
    [self displayViewController:moreVC];
    NSLog(@"跳转更多界面");
}

#pragma mark - configurate
- (void)configeration
{
    self.rows = 3;
    self.items = [[NSArray alloc] init];
    self.images = [[NSArray alloc] init];
}
static CGFloat HEIGHT_OF_ADVIEW = 120;
- (void)configurateAdImageView {
    self.adView = [[GJAutoCycleScrollView alloc] initWithFrame:CGRectMake(0, NAV_BAR_H,SCREEN_W, HEIGHT_OF_ADVIEW)];
    self.adView.delegate = self;
    self.adView.dataSource = self;
    self.adView.timeIntervalForAutoScroll = 5;
    [self.view addSubview:self.adView];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeItemCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"HomeItemCell"];
    cell.item = self.items[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"选中%ld",(long)indexPath.row);
    
    ItemDetailViewController *itemDetailVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ItemDetailViewController"];
    itemDetailVC.itemId = self.items[indexPath.row].itemId;
    if (self.items[indexPath.row].itemStatus == 9) {
        itemDetailVC.benefitStepStr = self.items[indexPath.row].gdBenefitReturnStep;
    }
    [self displayViewController:itemDetailVC];
}
//处理tableview分割线 左偏移问题
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - GJAutoCycleScrollViewDataSource
- (NSInteger)numberOfPagesInAutoCycleScrollView:(GJAutoCycleScrollView *)autoCycleScrollView {
    return [self.images count];
}

- (NSString *)autoCycleScrollView:(GJAutoCycleScrollView *)autoCycleScrollView imageUrlAtIndex:(NSInteger)index {
    //return self.adImages[index].imagePath;
    //http://img.zcool.cn/community/0125895659b67a6ac7251be89b337e.png
    //http://pic.qiantucdn.com/58pic/18/53/62/19a58PIC2gN_1024.jpg
    
//    if (index == 0) {
//        return @"http://img.zcool.cn/community/0125895659b67a6ac7251be89b337e.png";
//    }
//    if (index == 1) {
//        return @"http://pic.qiantucdn.com/58pic/18/53/62/19a58PIC2gN_1024.jpg";
//    }
//    if (index == 2) {
//        return @"http://pic.58pic.com/58pic/11/72/85/90w58PIC9I8.jpg";
//    }
//    
//    return @"http://img.zcool.cn/community/0125895659b67a6ac7251be89b337e.png";
    NSLog(@"image=%@",ConnectUrl(self.images[index].imageUrl));
    return  ConnectUrl(self.images[index].imageUrl);
    
}

@end
